import { useEffect, useMemo, useState } from "react";
import {
  Button,
  Card,
  Col,
  DatePicker,
  Descriptions,
  Empty,
  Form,
  Input,
  message,
  Modal,
  Select,
  Row,
  Space,
  Spin,
  Table,
  Tabs,
  Tag,
  Typography,
} from "antd";
import {
  DeleteOutlined,
  FileSearchOutlined,
  FundProjectionScreenOutlined,
  HistoryOutlined,
  PieChartOutlined,
  ReloadOutlined,
  SearchOutlined,
} from "@ant-design/icons";
import ReactECharts from "echarts-for-react";
import {
  batchDeleteApiLogs,
  deleteApiLog,
  getApiAverageSpeed,
  getApiLogs,
  getTop10CalledApis,
} from "../api/apiLogs";
import { isAdmin } from "../utils/auth";
import { useTheme } from "../contexts/ThemeContext";

const { RangePicker } = DatePicker;
const { Title, Text } = Typography;

const DATE_TIME_FORMAT = "YYYY-MM-DD HH:mm:ss";

const API_METHODS = ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"];

export default function ApiLogs() {
  const [form] = Form.useForm();
  const { isDarkMode } = useTheme();

  const [activeTab, setActiveTab] = useState("logs");

  const [logsLoading, setLogsLoading] = useState(false);
  const [logsData, setLogsData] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [filters, setFilters] = useState({});

  const [detailModalOpen, setDetailModalOpen] = useState(false);
  const [detailRecord, setDetailRecord] = useState(null);

  const [analysisLoading, setAnalysisLoading] = useState(false);
  const [averageSpeedData, setAverageSpeedData] = useState([]);
  const [top10Data, setTop10Data] = useState([]);

  const tableColumns = useMemo(
    () => [
      {
        title: "用户名",
        dataIndex: "username",
        width: 140,
        render: (value) => <Tag color="blue">{value || "匿名用户"}</Tag>,
      },
      {
        title: "接口描述",
        dataIndex: "apiDescription",
        ellipsis: true,
        width: 240,
      },
      {
        title: "请求路径",
        dataIndex: "apiPath",
        ellipsis: true,
        width: 220,
        render: (value) => <Text copyable>{value}</Text>,
      },
      {
        title: "请求方法",
        dataIndex: "apiMethod",
        width: 110,
        render: (value) => <Tag color="geekblue">{value}</Tag>,
      },
      {
        title: "响应耗时(ms)",
        dataIndex: "responseTime",
        align: "right",
        width: 130,
        render: (value) => (
          <Tag
            color={value >= 1000 ? "red" : value >= 300 ? "orange" : "green"}>
            {value}
          </Tag>
        ),
      },
      {
        title: "记录时间",
        dataIndex: "createdAt",
        width: 180,
      },
      {
        title: "操作",
        key: "actions",
        fixed: "right",
        width: 180,
        render: (_, record) => (
          <Space>
            <Button type="link" onClick={() => openDetail(record)}>
              详情
            </Button>
            <Button
              type="link"
              danger
              icon={<DeleteOutlined />}
              onClick={() => confirmDelete(record)}>
              删除
            </Button>
          </Space>
        ),
      },
    ],
    []
  );

  const loadLogs = async ({ current, pageSize, filtersOverride } = {}) => {
    setLogsLoading(true);
    try {
      const effectiveFilters = filtersOverride ?? filters;
      const params = {
        page: current || pagination.current,
        size: pageSize || pagination.pageSize,
        ...effectiveFilters,
      };
      const res = await getApiLogs(params);
      if (res.code !== 1) {
        throw new Error(res.msg || "获取API日志失败");
      }
      const data = res.data || {};
      setLogsData(data.list || []);
      setSelectedRowKeys([]);
      setPagination({
        current: params.page,
        pageSize: params.size,
        total: data.total || 0,
      });
    } catch (error) {
      message.error(error.message || "获取API日志失败");
      setLogsData([]);
      setPagination((prev) => ({ ...prev, total: 0 }));
    } finally {
      setLogsLoading(false);
    }
  };

  useEffect(() => {
    if (!isAdmin()) return;
    loadLogs();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const handleTableChange = (pager) => {
    loadLogs({ current: pager.current, pageSize: pager.pageSize });
  };

  const openDetail = (record) => {
    setDetailRecord(record);
    setDetailModalOpen(true);
  };

  const confirmDelete = (record) => {
    Modal.confirm({
      title: "确认删除该日志记录吗？",
      content: (
        <div>
          <div>接口描述：{record.apiDescription}</div>
          <div>请求路径：{record.apiPath}</div>
        </div>
      ),
      okType: "danger",
      onOk: () => handleDelete(record._id),
    });
  };

  const handleDelete = async (id) => {
    try {
      await deleteApiLog(id);
      message.success("删除成功");
      setSelectedRowKeys((prev) => prev.filter((key) => key !== id));
      loadLogs();
    } catch (error) {
      message.error(error.message || "删除失败");
    }
  };

  const handleBatchDelete = () => {
    if (selectedRowKeys.length === 0) {
      message.warning("请至少选择一条记录");
      return;
    }
    Modal.confirm({
      title: `确认删除选中的 ${selectedRowKeys.length} 条日志吗？`,
      okType: "danger",
      onOk: async () => {
        try {
          await batchDeleteApiLogs(selectedRowKeys);
          message.success("批量删除成功");
          setSelectedRowKeys([]);
          loadLogs();
        } catch (error) {
          message.error(error.message || "批量删除失败");
        }
      },
    });
  };

  const applyFilters = () => {
    form
      .validateFields()
      .then((values) => {
        const newFilters = {};
        const username = values.username?.trim();
        if (username) newFilters.username = username;
        const description = values.apiDescription?.trim();
        if (description) newFilters.apiDescription = description;
        const path = values.apiPath?.trim();
        if (path) newFilters.apiPath = path;
        if (values.apiMethod) newFilters.apiMethod = values.apiMethod;
        if (values.timeRange && values.timeRange.length === 2) {
          newFilters.startTime = values.timeRange[0].format(DATE_TIME_FORMAT);
          newFilters.endTime = values.timeRange[1].format(DATE_TIME_FORMAT);
        }
        setPagination((prev) => ({ ...prev, current: 1 }));
        setFilters(newFilters);
        loadLogs({ current: 1, filtersOverride: newFilters });
      })
      .catch(() => {
        message.error("请检查筛选条件");
      });
  };

  const resetFilters = () => {
    form.resetFields();
    setFilters({});
    setPagination((prev) => ({ ...prev, current: 1 }));
    loadLogs({ current: 1, filtersOverride: {} });
  };

  const loadAnalysisData = async () => {
    setAnalysisLoading(true);
    try {
      const [averageRes, topRes] = await Promise.all([
        getApiAverageSpeed(),
        getTop10CalledApis(),
      ]);
      if (averageRes.code !== 1) {
        throw new Error(averageRes.msg || "获取平均速率数据失败");
      }
      if (topRes.code !== 1) {
        throw new Error(topRes.msg || "获取调用次数数据失败");
      }
      setAverageSpeedData(averageRes.data || []);
      setTop10Data(topRes.data || []);
    } catch (error) {
      message.error(error.message || "获取分析数据失败");
      setAverageSpeedData([]);
      setTop10Data([]);
    } finally {
      setAnalysisLoading(false);
    }
  };

  useEffect(() => {
    if (
      activeTab === "analysis" &&
      top10Data.length === 0 &&
      averageSpeedData.length === 0
    ) {
      loadAnalysisData();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [activeTab]);

  const averageTableData = useMemo(
    () =>
      averageSpeedData.map((item, index) => {
        const avg = Number(item.avg_response_time ?? 0);
        return {
          key: `${item.api_path}-${item.api_method}-${index}`,
          description: item.api_description || "-",
          path: item.api_path,
          method: item.api_method,
          count: item.count ?? 0,
          avg,
        };
      }),
    [averageSpeedData]
  );

  const averageColumns = useMemo(
    () => [
      {
        title: "接口描述",
        dataIndex: "description",
        ellipsis: true,
      },
      {
        title: "请求路径",
        dataIndex: "path",
        ellipsis: true,
        render: (value) => <Text copyable>{value}</Text>,
      },
      {
        title: "请求方法",
        dataIndex: "method",
        width: 120,
        render: (value) => <Tag color="geekblue">{value}</Tag>,
      },
      {
        title: "调用次数",
        dataIndex: "count",
        width: 120,
        align: "right",
      },
      {
        title: "平均耗时(ms)",
        dataIndex: "avg",
        width: 160,
        align: "right",
        render: (value) => {
          const numericValue = Number(value) || 0;
          const color =
            numericValue >= 1000
              ? "red"
              : numericValue >= 500
              ? "orange"
              : "green";
          return <Tag color={color}>{numericValue.toFixed(2)}</Tag>;
        },
      },
    ],
    []
  );

  const top10ChartOption = useMemo(() => {
    if (!top10Data.length) return null;
    const colors = isDarkMode
      ? { text: "#ddd", legend: "#eee" }
      : { text: "#333", legend: "#333" };
    return {
      backgroundColor: "transparent",
      tooltip: {
        trigger: "item",
        formatter: (params) =>
          `${params.name}<br/>调用次数：${
            params.value
          } (${params.percent.toFixed(1)}%)`,
      },
      legend: {
        type: "scroll",
        orient: "vertical",
        left: 0,
        top: 20,
        bottom: 20,
        textStyle: {
          color: colors.legend,
        },
        maxHeight: 400,
      },
      series: [
        {
          name: "调用次数",
          type: "pie",
          radius: ["35%", "65%"],
          center: ["55%", "50%"],
          avoidLabelOverlap: true,
          label: {
            color: colors.text,
            formatter: (params) => {
              const displayName =
                params.name.length > 20
                  ? params.name.substring(0, 17) + "..."
                  : params.name;
              return `${displayName}\n${params.value}次`;
            },
            fontSize: 11,
          },
          labelLine: {
            length: 15,
            length2: 8,
            smooth: true,
          },
          data: top10Data.map((item) => ({
            name: item.api_description || item.api_path,
            value: item.call_count,
          })),
        },
      ],
    };
  }, [top10Data, isDarkMode]);

  if (!isAdmin()) {
    return (
      <div style={{ maxWidth: 1200, margin: "20px auto", padding: "0 16px" }}>
        <Card style={{ textAlign: "center", padding: "60px 20px" }}>
          <Title level={3} type="danger">
            权限不足
          </Title>
          <Text type="secondary" style={{ fontSize: 16 }}>
            抱歉，您没有权限访问 API 调用日志模块。
          </Text>
        </Card>
      </div>
    );
  }

  return (
    <div style={{ maxWidth: 1200, margin: "20px auto", padding: "0 16px" }}>
      <div style={{ textAlign: "center", marginBottom: 24 }}>
        <Title level={2} style={{ color: "#1890ff", marginBottom: 8 }}>
          <HistoryOutlined /> API 调用日志
        </Title>
        <Text type="secondary" style={{ fontSize: 16 }}>
          基于 NestJS 和 FastAPI 的接口调用追踪与分析
        </Text>
      </div>

      <Tabs
        activeKey={activeTab}
        onChange={(key) => setActiveTab(key)}
        items={[
          {
            key: "logs",
            label: (
              <Space>
                <FileSearchOutlined /> API 日志
              </Space>
            ),
            children: (
              <Card
                bordered={false}
                style={{
                  borderRadius: 12,
                  boxShadow: isDarkMode
                    ? "0 2px 12px rgba(0,0,0,0.3)"
                    : "0 2px 12px #eee",
                  backgroundColor: isDarkMode ? "#1f1f1f" : "#ffffff",
                  borderColor: isDarkMode ? "#434343" : "#d9d9d9",
                  transition: "all 0.3s ease",
                }}>
                {/* 搜索条件 - 单独的Card */}
                <Card
                  size="small"
                  title={
                    <Space>
                      <SearchOutlined />
                      <span>搜索条件</span>
                    </Space>
                  }
                  style={{
                    marginBottom: 24,
                    backgroundColor: isDarkMode ? "#262626" : "#fafafa",
                    borderColor: isDarkMode ? "#434343" : "#d9d9d9",
                  }}>
                  <Form
                    form={form}
                    layout="inline"
                    initialValues={{
                      apiMethod: undefined,
                      timeRange: undefined,
                    }}>
                    {/* 第一行:搜索条件 */}
                    <Row gutter={[12, 12]} style={{ width: "100%" }}>
                      <Col xs={24} sm={12} md={8}>
                        <Form.Item
                          name="apiPath"
                          style={{ marginBottom: 0, width: "100%" }}>
                          <Input
                            allowClear
                            placeholder="请求路径"
                            prefix={<SearchOutlined />}
                          />
                        </Form.Item>
                      </Col>
                      <Col xs={24} sm={12} md={8}>
                        <Form.Item
                          name="username"
                          style={{ marginBottom: 0, width: "100%" }}>
                          <Input allowClear placeholder="用户名" />
                        </Form.Item>
                      </Col>
                      <Col xs={24} sm={12} md={8}>
                        <Form.Item
                          name="apiDescription"
                          style={{ marginBottom: 0, width: "100%" }}>
                          <Input allowClear placeholder="接口描述" />
                        </Form.Item>
                      </Col>
                    </Row>

                    {/* 第二行:其他搜索条件 */}
                    <Row
                      gutter={[12, 12]}
                      style={{ marginTop: 12, width: "100%" }}>
                      <Col xs={24} sm={12} md={8}>
                        <Form.Item
                          name="apiMethod"
                          style={{ marginBottom: 0, width: "100%" }}>
                          <Select
                            placeholder="方法"
                            allowClear
                            style={{ width: "100%" }}>
                            {API_METHODS.map((method) => (
                              <Select.Option key={method} value={method}>
                                {method}
                              </Select.Option>
                            ))}
                          </Select>
                        </Form.Item>
                      </Col>
                      <Col xs={24} sm={12} md={8}>
                        <Form.Item
                          name="timeRange"
                          style={{ marginBottom: 0, width: "100%" }}>
                          <RangePicker
                            showTime={{ format: "HH:mm:ss" }}
                            format={DATE_TIME_FORMAT}
                            style={{ width: "100%" }}
                            allowClear
                            placeholder={["开始时间", "结束时间"]}
                          />
                        </Form.Item>
                      </Col>
                      <Col xs={24} sm={12} md={8}>
                        <Form.Item style={{ marginBottom: 0, width: "100%" }}>
                          <Space style={{ width: "100%" }}>
                            <Button
                              type="primary"
                              icon={<SearchOutlined />}
                              onClick={applyFilters}>
                              搜索
                            </Button>
                            <Button
                              icon={<ReloadOutlined />}
                              onClick={resetFilters}>
                              重置
                            </Button>
                          </Space>
                        </Form.Item>
                      </Col>
                    </Row>
                  </Form>
                </Card>

                {/* 操作按钮 */}
                <div style={{ marginBottom: 16 }}>
                  <Space>
                    <Button
                      type="primary"
                      danger
                      icon={<DeleteOutlined />}
                      onClick={handleBatchDelete}
                      disabled={selectedRowKeys.length === 0}>
                      批量删除 ({selectedRowKeys.length})
                    </Button>
                    <Button
                      type="primary"
                      icon={<ReloadOutlined />}
                      onClick={() =>
                        loadLogs({
                          current: 1,
                          filtersOverride: form.getFieldsValue(),
                        })
                      }>
                      刷新
                    </Button>
                  </Space>
                </div>

                <Table
                  rowKey="_id"
                  columns={tableColumns}
                  dataSource={logsData}
                  loading={logsLoading}
                  pagination={pagination}
                  onChange={handleTableChange}
                  scroll={{ x: 1100 }}
                  rowSelection={{
                    selectedRowKeys,
                    onChange: setSelectedRowKeys,
                  }}
                  expandable={{
                    expandedRowRender: (record) => (
                      <div
                        style={{
                          background: isDarkMode ? "#1f1f1f" : "#fafafa",
                          padding: 12,
                          borderRadius: 8,
                        }}>
                        <Descriptions column={1} size="small" bordered>
                          <Descriptions.Item label="Query Params">
                            <pre style={{ margin: 0 }}>
                              {record.queryParams
                                ? JSON.stringify(record.queryParams, null, 2)
                                : "-"}
                            </pre>
                          </Descriptions.Item>
                          <Descriptions.Item label="Path Params">
                            <pre style={{ margin: 0 }}>
                              {record.pathParams
                                ? JSON.stringify(record.pathParams, null, 2)
                                : "-"}
                            </pre>
                          </Descriptions.Item>
                          <Descriptions.Item label="Request Body">
                            <pre style={{ margin: 0 }}>
                              {record.requestBody
                                ? JSON.stringify(record.requestBody, null, 2)
                                : "-"}
                            </pre>
                          </Descriptions.Item>
                          <Descriptions.Item label="更新时间">
                            {record.updatedAt}
                          </Descriptions.Item>
                        </Descriptions>
                      </div>
                    ),
                  }}
                  locale={{
                    emptyText: logsLoading ? (
                      <Spin />
                    ) : (
                      <Empty description="暂无数据" />
                    ),
                  }}
                />
              </Card>
            ),
          },
          {
            key: "analysis",
            label: (
              <Space>
                <FundProjectionScreenOutlined /> 数据分析
              </Space>
            ),
            children: (
              <Card
                bordered={false}
                style={{
                  borderRadius: 12,
                  boxShadow: isDarkMode
                    ? "0 2px 12px rgba(0,0,0,0.3)"
                    : "0 2px 12px #eee",
                  backgroundColor: isDarkMode ? "#1f1f1f" : "#ffffff",
                  borderColor: isDarkMode ? "#434343" : "#d9d9d9",
                  transition: "all 0.3s ease",
                }}
                extra={
                  <Button
                    icon={<ReloadOutlined />}
                    onClick={loadAnalysisData}
                    loading={analysisLoading}
                    type="primary">
                    刷新数据
                  </Button>
                }>
                {analysisLoading ? (
                  <div style={{ textAlign: "center", padding: "80px 0" }}>
                    <Spin size="large" />
                  </div>
                ) : (
                  <Tabs
                    destroyInactiveTabPane
                    items={[
                      {
                        key: "average",
                        label: (
                          <Space>
                            <PieChartOutlined style={{ color: "#1890ff" }} />
                            平均耗时
                          </Space>
                        ),
                        children: (
                          <Card
                            bodyStyle={{ padding: 0 }}
                            bordered={false}
                            style={{
                              borderRadius: 12,
                              backgroundColor: isDarkMode
                                ? "#141414"
                                : "#ffffff",
                              border: `1px solid ${
                                isDarkMode ? "#434343" : "#d9d9d9"
                              }`,
                              boxShadow: isDarkMode
                                ? "0 2px 12px rgba(0,0,0,0.25)"
                                : "0 2px 12px #f2f2f2",
                              padding: 24,
                            }}
                            title={
                              <Space>
                                <PieChartOutlined
                                  style={{ color: "#1890ff" }}
                                />
                                API 平均响应耗时
                              </Space>
                            }
                            extra={<Tag color="blue">单位：毫秒</Tag>}>
                            {averageSpeedData.length ? (
                              <Table
                                columns={averageColumns}
                                dataSource={averageTableData}
                                pagination={false}
                                size="middle"
                              />
                            ) : (
                              <Empty
                                image={Empty.PRESENTED_IMAGE_SIMPLE}
                                description="暂无平均速率数据"
                                style={{ padding: "40px 0" }}
                              />
                            )}
                          </Card>
                        ),
                      },
                      {
                        key: "top10",
                        label: (
                          <Space>
                            <FundProjectionScreenOutlined
                              style={{ color: "#52c41a" }}
                            />
                            调用次数
                          </Space>
                        ),
                        children: (
                          <Card
                            bodyStyle={{ padding: 0 }}
                            bordered={false}
                            style={{
                              borderRadius: 12,
                              backgroundColor: isDarkMode
                                ? "#141414"
                                : "#ffffff",
                              border: `1px solid ${
                                isDarkMode ? "#434343" : "#d9d9d9"
                              }`,
                              boxShadow: isDarkMode
                                ? "0 2px 12px rgba(0,0,0,0.25)"
                                : "0 2px 12px #f2f2f2",
                              padding: 24,
                            }}
                            title={
                              <Space>
                                <FundProjectionScreenOutlined
                                  style={{ color: "#52c41a" }}
                                />
                                调用次数分布
                              </Space>
                            }
                            extra={<Tag color="green">按调用次数排序</Tag>}>
                            {top10Data.length ? (
                              <ReactECharts
                                option={top10ChartOption}
                                style={{ height: 580 }}
                              />
                            ) : (
                              <Empty
                                image={Empty.PRESENTED_IMAGE_SIMPLE}
                                description="暂无调用次数数据"
                                style={{ padding: "40px 0" }}
                              />
                            )}
                          </Card>
                        ),
                      },
                    ]}
                  />
                )}
              </Card>
            ),
          },
        ]}
      />

      <Modal
        title="API 调用详情"
        open={detailModalOpen}
        onCancel={() => setDetailModalOpen(false)}
        footer={[
          <Button key="close" onClick={() => setDetailModalOpen(false)}>
            关闭
          </Button>,
        ]}
        width={720}
        styles={{
          content: { backgroundColor: isDarkMode ? "#141414" : "#ffffff" },
          header: {
            backgroundColor: isDarkMode ? "#1f1f1f" : "#ffffff",
            borderBottom: `1px solid ${isDarkMode ? "#434343" : "#f0f0f0"}`,
          },
          body: { backgroundColor: isDarkMode ? "#141414" : "#ffffff" },
        }}>
        {detailRecord && (
          <Descriptions column={1} bordered size="middle">
            <Descriptions.Item label="用户名">
              <Tag color="blue">{detailRecord.username || "匿名用户"}</Tag>
            </Descriptions.Item>
            <Descriptions.Item label="接口描述">
              {detailRecord.apiDescription || "-"}
            </Descriptions.Item>
            <Descriptions.Item label="请求路径">
              <Text copyable>{detailRecord.apiPath}</Text>
            </Descriptions.Item>
            <Descriptions.Item label="请求方法">
              <Tag color="geekblue">{detailRecord.apiMethod}</Tag>
            </Descriptions.Item>
            <Descriptions.Item label="响应耗时">
              <Tag
                color={
                  detailRecord.responseTime >= 1000
                    ? "red"
                    : detailRecord.responseTime >= 300
                    ? "orange"
                    : "green"
                }>
                {detailRecord.responseTime} ms
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="请求时间">
              {detailRecord.createdAt}
            </Descriptions.Item>
            <Descriptions.Item label="更新时间">
              {detailRecord.updatedAt}
            </Descriptions.Item>
            <Descriptions.Item label="Query Params">
              <pre style={{ margin: 0 }}>
                {detailRecord.queryParams
                  ? JSON.stringify(detailRecord.queryParams, null, 2)
                  : "-"}
              </pre>
            </Descriptions.Item>
            <Descriptions.Item label="Path Params">
              <pre style={{ margin: 0 }}>
                {detailRecord.pathParams
                  ? JSON.stringify(detailRecord.pathParams, null, 2)
                  : "-"}
              </pre>
            </Descriptions.Item>
            <Descriptions.Item label="Request Body">
              <pre style={{ margin: 0 }}>
                {detailRecord.requestBody
                  ? JSON.stringify(detailRecord.requestBody, null, 2)
                  : "-"}
              </pre>
            </Descriptions.Item>
          </Descriptions>
        )}
      </Modal>
    </div>
  );
}
